package com.iflytek.exam.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.iflytek.common.utils.DateUtils;
import com.iflytek.common.utils.SecurityUtils;
import com.iflytek.exam.domain.ExamTeacher;
import com.iflytek.exam.domain.QuestionExam;
import com.iflytek.exam.domain.TbQuestionSummary;
import com.iflytek.exam.service.*;
import com.iflytek.exam.vo.ExamVo;
import com.iflytek.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.iflytek.exam.mapper.CreateExamMapper;
import com.iflytek.exam.domain.CreateExam;

import static com.iflytek.exam.utils.RandomCom.getRandomChoiceIds;

/**
 * 创建考试基本信息Service业务层处理
 *
 * @author Dogdog
 * @date 2024-07-08
 */
@Service
public class CreateExamServiceImpl implements ICreateExamService
{
    @Autowired
    private ICreateExamService createExamService;
    @Autowired
    private CreateExamMapper createExamMapper;
    @Autowired
    private IChoiceService choiceService;
    @Autowired
    private QuestionExamService questionExamService;
    @Autowired
    private IJudgeService judgeService;
    @Autowired
    private IShortAnswerService shortAnswerService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IExamTeacherService examTeacherService;
    @Autowired
    private ITbQuestionSummaryService questionSummaryService;
    @Autowired
    private IExamSetService examSetService;



    @Override
    public String sureIf(ExamVo examVo) {
        Long singleWhich = examVo.getSingleWhich(); //用户输入单选题题数量
        Long judgeWhich = examVo.getJudgeWhich(); //用户输入判断题数量
        Long multipleWhich = examVo.getMultipleWhich(); //用户输入多选题数量
        Long shortAnswerWhich = examVo.getShortAnswerWhich(); //用户输入简答题数量
        long quBankId = examVo.getQuBankId();
        //这里获取下题库的名称
        TbQuestionSummary tbQuestionSummary = questionSummaryService.selectTbQuestionSummaryById(quBankId);
        String summaryName = tbQuestionSummary.getName();

        //查询所有的单选的id（数组）
        Long[] radioIds =choiceService.getAllChoiceRadioIds(quBankId);
        //查询所有多选的id（数组）
        Long[] checkIds =choiceService.getAllChoiceCheckIds(quBankId);
        //查询所有的判断题id（数组）
        Long[] judgeIds =judgeService.getAllJudgeIds(quBankId);
        //查询所有简答题的id（数组）
        Long[] shortAnswerIds =shortAnswerService.getAllShortAnswerIds(quBankId);
        //用户输入的要小于查询到的（题库有的），否则就提示题库中试题数量不足，请先添加试题;
        if (singleWhich > radioIds.length){
            return "所选" + "*" +summaryName + "*" + "题库中单选题数量不足，有" +radioIds.length + "道试题，请先添加试题";
        }else
        if (judgeWhich > judgeIds.length){
            return "所选" + "*" + summaryName+ "*" + "题库中判断题数量不足，有" +judgeIds.length + "道试题，请先添加试题";
        }else
        if (multipleWhich > checkIds.length){
            return "所选" + "*" + summaryName+ "*" + "题库中多选题数量不足，有" +checkIds.length + "道试题，请先添加试题";
        }else
        if (shortAnswerWhich > shortAnswerIds.length){
            return "所选" + "*" + summaryName+ "*" + "题库中简答题数量不足，有" +shortAnswerIds.length + "道试题，请先添加试题";
        }else {
            return "1";
        }
    }

    /**
     * 随机分发试卷
     * @param examVo
     * @param ids
     * @param uuid
     * @return
     */
    @Override
    public boolean distribute(ExamVo examVo, Long[] ids, String uuid) {
        Long radio = examVo.getSingleWhich(); //用户输入单选题题数量
        Long judge = examVo.getJudgeWhich(); //用户输入判断题数量
        Long check = examVo.getMultipleWhich(); //用户输入多选题数量
        Long shortAnswer = examVo.getShortAnswerWhich(); //用户输入简答题数量
        long quBankId = examVo.getQuBankId(); //题库的id（是要根据题库的id进行抽题的）
        try {
            //查询所有的单选的id（数组）
            Long[] radioIds =choiceService.getAllChoiceRadioIds(quBankId);
            //查询所有多选的id（数组）
            Long[] checkIds =choiceService.getAllChoiceCheckIds(quBankId);
            //查询所有的判断题id（数组）
            Long[] judgeIds =judgeService.getAllJudgeIds(quBankId);
            //查询所有简答题的id（数组）
            Long[] shortAnswerIds =shortAnswerService.getAllShortAnswerIds(quBankId);

            Long examId = createExamService.getExamIdByUuid(uuid); //试卷的id
            System.out.println("examId:"+examId);

            //1.获取所有被选中学生的ids
            for (int i = 0; i < ids.length; i++){
                Long user_id = ids[i]; //学生的user_id
                //2.选择题随机组卷
                if (radio > 0){
                    // 调用方法抽取 ID，这就是抽取到的所有选择题的ids
                    Long[] randomChoiceIds = getRandomChoiceIds(radioIds, radio);
                    for (int j = 0; j < randomChoiceIds.length; j++){
                        QuestionExam questionExam = new QuestionExam();
                        Long choiceId = randomChoiceIds[j]; //选择题的id
                        //查找单选题的类型
                        //3.将学生id，选择题id，试卷id插入到试卷试题表
                        questionExam.setUserId(user_id);
                        questionExam.setExamId(examId);
                        questionExam.setQuestionId(choiceId);
                        questionExam.setType(1);
                        questionExamService.insertQuestionExam(questionExam);
                    }
                }
                if (check > 0){
                    // 调用方法抽取 ID，这就是抽取到的所有多选题的ids
                    Long[] randomChoiceCheckIds = getRandomChoiceIds(checkIds, check);
                    for (int j = 0; j < randomChoiceCheckIds.length; j++){
                        QuestionExam questionExam = new QuestionExam();
                        Long choiceCheckId = randomChoiceCheckIds[j]; //多选题的id
                        //查找选择题的类型
                        //3.将学生id，选择题id，试卷id插入到试卷试题表
                        questionExam.setUserId(user_id);
                        questionExam.setExamId(examId);
                        questionExam.setQuestionId(choiceCheckId);
                        questionExam.setType(2);
                        questionExamService.insertQuestionExam(questionExam);
                    }
                }
                if (judge > 0){
                    // 调用方法抽取 ID，这就是抽取到的所有多选题的ids
                    Long[] randomChoiceJudgeIds = getRandomChoiceIds(judgeIds, judge);
                    for (int j = 0; j < randomChoiceJudgeIds.length; j++){
                        QuestionExam questionExam = new QuestionExam();
                        Long JudgeId = randomChoiceJudgeIds[j]; //多选题的id
                        //查找选择题的类型
                        //3.将学生id，选择题id，试卷id插入到试卷试题表
                        questionExam.setUserId(user_id);
                        questionExam.setExamId(examId);
                        questionExam.setQuestionId(JudgeId);
                        questionExam.setType(3);
                        questionExamService.insertQuestionExam(questionExam);
                    }
                }
                if (shortAnswer > 0){
                    // 调用方法抽取 ID，这就是抽取到的所有多选题的ids
                    Long[] randomShortAnswerIdsIds = getRandomChoiceIds(shortAnswerIds, shortAnswer);
                    for (int j = 0; j < randomShortAnswerIdsIds.length; j++){
                        QuestionExam questionExam = new QuestionExam();
                        Long shortAnswerId = randomShortAnswerIdsIds[j]; //多选题的id
                        //查找选择题的类型
                        //3.将学生id，选择题id，试卷id插入到试卷试题表
                        questionExam.setUserId(user_id);
                        questionExam.setExamId(examId);
                        questionExam.setQuestionId(shortAnswerId);
                        questionExam.setType(4);
                        questionExamService.insertQuestionExam(questionExam);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            // 如果发生异常，打印堆栈跟踪（可选）
            e.printStackTrace();
            // 返回 false 表示发生错误
            return false;
        }
    }

    @Override
    public CreateExam getCreateExam(Long[] examIds) {
        //通过ids查询出考试基本信息表
        CreateExam createExam = new CreateExam();
        return createExamMapper.getCreateExamByIds(examIds);
    }

    @Override
    public Boolean deleteAllExam(Long examId) {
        //删除试卷表，试卷—-权限关联表，试卷-教师关联表，试卷-题关联表
        createExamMapper.deletecreateExamById(examId); //删除试卷表
        Boolean a = examTeacherService.deleteExamTeacherByExamId(examId); //删除试卷--教师关联表
        Boolean b =  questionExamService.deleteQuestionExamByExamId(examId); //删除试卷--题关联表
        Boolean c=  examSetService.deleteExamSetByExamId(examId);
        //如果abc都是true，返回true
        if (a && b && c){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<CreateExam> selectcreateExamListByUserId(CreateExam createExam) {
        List<CreateExam> createExamList = new ArrayList<>();
        List<QuestionExam> questionExamList = new ArrayList<>();
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            questionExamList = questionExamService.selectPaperQuestionForAll();
        }else {
            questionExamList = questionExamService.selectPaperQuestionByUserId(SecurityUtils.getUserId());
        }
        questionExamList.forEach(questionExam -> {
            CreateExam exam = this.selectcreateExamById(questionExam.getExamId());
            createExamList.add(exam);
        });
        return createExamList;
    }


    /**
     * 查询创建考试基本信息
     *
     * @param id 创建考试基本信息主键
     * @return 创建考试基本信息
     */
    @Override
    public CreateExam selectcreateExamById(Long id)
    {
        return createExamMapper.selectcreateExamById(id);
    }

    /**
     * 查询创建考试基本信息列表
     *
     * @param createExam 创建考试基本信息
     * @return 创建考试基本信息
     */
    @Override
    public List<CreateExam> selectcreateExamList(CreateExam createExam)
    {
        return createExamMapper.selectcreateExamList(createExam);
    }

    /**
     * 根据登陆教师用户展示考试列表
     * @param createExam
     * @return
     */
    @Override
    public List<CreateExam> selectlistExamTwo(CreateExam createExam)
    {
        //TODO 到时候这个接口直接打开测试就行，逻辑已实现
        //1.这个是按照那个老师登录就让哪个老师查看自己创建的试卷
        String name = SecurityContextHolder.getContext().getAuthentication().getName();//获取当前登录的用户id
        Long userId = sysUserService.selectUserByUserName(name).getUserId(); //找到登录人的id
        Long[] examIds = examTeacherService.selectExamIds(userId);
        CreateExam createExam1 =createExamService.getCreateExam(examIds);
        return createExamMapper.selectlistExamTwo(createExam1);
        //2.谁登录都可以查看所有的试卷
        //return createExamMapper.selectlistExamTwo(createExam);
    }


    /**
     * 新增创建考试基本信息
     *
     * @param createExam 创建考试基本信息
     * @return 结果
     */
    @Override
    public int insertcreateExam(CreateExam createExam)
    {
        createExam.setCreateTime(DateUtils.getNowDate());
        return createExamMapper.insertcreateExam(createExam);
    }

    /**
     * 创建试卷
     * @param examVo
     * @return
     */
    @Override
    public List insertExam(ExamVo examVo) {
        CreateExam createExam = new CreateExam();
        //获取所有的信息
        String name = examVo.getName(); //考试名称
        String info = examVo.getInfo(); //考试说明
        Date startTime = examVo.getStartTime(); //考试开始时间
        Date endTime = examVo.getEndTime(); //考试结束时间
        Long time = examVo.getTime(); //考试答题允许时间
        Long singleScore = examVo.getSingleScore(); //单选题分数
        Long multipleScore = examVo.getMultipleScore(); //多选题分数
        Long shortAnswerScore = examVo.getShortAnswerScore(); //简答题分数
        Long judgeScore = examVo.getJudgeScore(); //判断题分数
        Long singleWhich = examVo.getSingleWhich(); //单选题个数
        Long multipleWhich = examVo.getMultipleWhich(); //多选题个数
        Long shortAnswerWhich = examVo.getShortAnswerWhich(); //简答题个数
        Long judgeWhich = examVo.getJudgeWhich(); //判断题个数

        //下面开始计算
        Long totalScore = singleScore * singleWhich + multipleScore * multipleWhich + shortAnswerScore * shortAnswerWhich + judgeScore * judgeWhich; //总分数
        Long passLine = totalScore * 60 / 100; //及格分
        //将上面所有数据添加到createExam对象中
        createExam.setName(name);
        createExam.setInfo(info);
        createExam.setStartTime(startTime);
        createExam.setEndTime(endTime);
        createExam.setTime(time);
        createExam.setTotalScore(totalScore);
        createExam.setPassLine(passLine);
        createExam.setTotalScore(totalScore);
        createExam.setPassLine(passLine);
        createExam.setSingleScore(singleScore);
        createExam.setMultipleScore(multipleScore);
        createExam.setShortAnswerScore(shortAnswerScore);
        createExam.setJudgeScore(judgeScore);
        createExam.setCreateTime(DateUtils.getNowDate());
        //生成10位的uuid
        UUID uuid = UUID.randomUUID();
        String shortUUID = uuid.toString().replaceAll("-", "").substring(0, 10);
        createExam.setImg(shortUUID);
        createExamMapper.insertcreateExam(createExam);
        //添加试卷和试题的中间表
        String teacherName = SecurityContextHolder.getContext().getAuthentication().getName();
        //System.out.println("______" + name);
        Long teacherId = sysUserService.selectUserByUserName(teacherName).getUserId();
        ExamTeacher examTeacher = new ExamTeacher();
        Long examId = createExamService.getExamIdByUuid(shortUUID);
        examTeacher.setExamId(examId);
        examTeacher.setUserId(teacherId);
        examTeacher.setCode(uuid.toString().replaceAll("-", "").substring(0, 9));
        examTeacherService.insertExamTeacher(examTeacher);
        ArrayList arrayList = new ArrayList();
        arrayList.add(shortUUID);
        return arrayList;
    }

    @Override
    public Long getExamIdByUuid(String uuid) {
        return createExamMapper.getExamIdByUuid(uuid);
    }


    /**
     * 修改创建考试基本信息
     *
     * @param createExam 创建考试基本信息
     * @return 结果
     */
    @Override
    public int updatecreateExam(CreateExam createExam)
    {
        createExam.setUpdateTime(DateUtils.getNowDate());
        return createExamMapper.updatecreateExam(createExam);
    }

    /**
     * 批量删除创建考试基本信息
     *
     * @param ids 需要删除的创建考试基本信息主键
     * @return 结果
     */
    @Override
    public int deletecreateExamByIds(Long[] ids)
    {
        return createExamMapper.deletecreateExamByIds(ids);
    }

    /**
     * 删除创建考试基本信息信息
     *
     * @param id 创建考试基本信息主键
     * @return 结果
     */
    @Override
    public int deletecreateExamById(Long id)
    {
        return createExamMapper.deletecreateExamById(id);
    }

}
